<!--
 * @Description: 角色管理
 * @Author: zhihong deng
 * @Date: 2021-08-23 21:31:35
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-09-20 20:01:36
-->
<template>
  <div class="role-manage">
    <!-- 条件查询 -->
    <div class="query-form">
      <el-form :inline="true" ref="form" :model="queryForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRoleList">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleCreate">创建</el-button>
      </div>
      <!-- 表格 -->
      <el-table
        :data="roleList">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          align="center"
          :formatter="item.formatter">
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" size="mini" @click="handleOpenPermission(scope.row)">设置权限</el-button>
            <el-button type="danger" size="mini" @click="handleDel(scope.row._id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    <!-- 新增角色弹框 -->
    <el-dialog
      title="用户新增"
      v-model="showModal"
      width="width"
      :before-close="dialogBeforeClose">
      <div>
        <el-form
          ref="dialogForm"
          :model="roleForm"
          label-width="80px"
          :rules="rules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              :rows="2"
              v-model="roleForm.remark"
              placeholder="请输入备注" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 权限弹框 -->
    <el-dialog
      title="权限设置"
      v-model="showPermission"
      :before-close="dialogBeforeClose">
      <div>
        <el-form label-width="80px">
          <el-form-item label="角色名称">
            {{ curRoleName }}
          </el-form-item>
          <el-form-item label="选择权限">
              <el-tree
                ref="permissionTree"
                :data="menuList"
                show-checkbox
                default-expand-all
                node-key="_id"
                :props="{label: 'menuName'}"
              >
              </el-tree>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermission = false">取 消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import utils from '../utils/utils'
export default {
  name: "role",
  data() {
    return {
      queryForm: {
        roleName: ""
      },
      roleList: [],
      columns: [
        {
          label: '角色名称',
          prop: 'roleName',
        },
        {
          label: '备注',
          prop: 'remark',
        },
        {
          label: '权限列表',
          prop: 'permissionList',
          width: 200,
          formatter: (row, column, value) => {
            let names = []
            let list = value.halfCheckedKeys || []
            list.map(key => {
              let name = this.actionMap[key]
              if (key && name) names.push(name)
            })
            return names.join(',')
          }
        },
        {
          label: '创建时间',
          prop: 'createTime',
          formatter: (row, column, value) => {
            return utils.formateDate(new Date(value));
          },
        },
        {
          label: '更新时间',
          prop: 'updateTime',
          formatter: (row, column, value) => {
            return utils.formateDate(new Date(value));
          },
        }
      ],
      pager: {
        total: 1,
        pageNum: 1,
        pageSize: 10,
      },
      showModal: false,
      roleForm: {
        // parentId: [null],
        // menuType: 1,
        // menuState: 1
      },
      action: '',
      rules:{
        roleName:[
          {required: true,message: "请输入角色名称",trigger: "blur"}
        ]
      },
      // 权限弹框
      showPermission: false,
      curRoleName: "",
      curRoleId: "",
      menuList: [],
      // 菜单映射表
      actionMap: {}
    }
  },
  mounted() {
    this.getRoleList()
    this.getMenuList()
  },
  methods: {
    // 角色列表初始化&查询
    async getRoleList() {
      try {
        let { list, page } = await this.$api.getRoleList({...this.queryForm, ...this.pager});
        this.roleList = list;
        this.pager.total = page.total
      } catch (error) {
        throw new Error(error);
      }
    },
    // 获取权限菜单列表
    async getMenuList() {
      try {
        let list = await this.$api.getMenuList();
        this.menuList = list;
        this.getActionMap(list)
      } catch (error) {
        throw new Error(error);
      }
    },
    // 重置
    handleReset(form) {
      this.$refs[form].resetFields()
    },
    // 分页事件处理
    handleCurrentChange (current) {
      this.pager.pageNum = current;
      this.getRoleList();
    },
    // 角色新增
    handleCreate () {
      this.showModal = true;
      this.action = "create"
    },
    // 编辑
    handleEdit(row) {
      this.showModal = true
      this.action = 'edit'
      // 在dom更新结束后才触发
      this.$nextTick(() => {
        // 浅拷贝，第一个参数是被赋值对象，第二个参数是要赋值的参数
       this.roleForm = {_id: row._id, roleName: row.roleName, remark: row.remark}
      })
    },
    // 删除
    async handleDel(_id) {
      await this.$api.roleOperate({_id, action:'delete'})
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 新增提交
    handleSubmit() {
      this.$refs.dialogForm.validate( async (valid) => {
        if(valid){
          // 解构赋值
          let { roleForm, action } = this
          // 接口需要参数
          let params = {...roleForm, action}
          let res = await this.$api.roleOperate(params)
          console.log('新增提交', res);
          if(res){
            this.showModal = false
            this.$message.success("创建成功")
            this.handleReset('dialogForm')
            this.getRoleList()
          }
        }
      })

    },
    // 关闭弹框
    handleClose() {
      this.showModal = false
      this.handleReset('dialogForm')
    },
    // 设置权限
    handleOpenPermission(row) {
      this.curRoleId = row._id
      this.showPermission = true
      this.curRoleName = row.roleName
      let { checkedKeys } = row.permissionList;
      setTimeout(() => {
        this.$refs.permissionTree.setCheckedKeys(checkedKeys)
      })
    },
    // 确认权限
    async handlePermissionSubmit() {
      // 获取节点
      let nodes = this.$refs.permissionTree.getCheckedNodes()
      let halfKeys = this.$refs.permissionTree.getHalfCheckedKeys()
      let checkedKeys= []
      let parentKeys = []
      // 遍历节点
      nodes.map(node => {
        if(!node.children){
          checkedKeys.push(node._id)
        } else {
          parentKeys.push(node._id)
        }
      })
      let params = {
        _id: this.curRoleId,
        permissionList: {
          checkedKeys, // 按钮菜单
          halfCheckedKeys: parentKeys.concat(halfKeys) // 一级菜单
        }
      }
      await this.$api.updatePermission(params)
      this.showPermission = false
      this.$message.success('设置成功')
      this.getRoleList()
    },
    // 遍历菜单列表
    getActionMap(list) {
      let actionMap = {};
      // 递归权限列表
      const deep = (arr) => {
        while (arr.length) {
          let item = arr.pop();
          if (item.children && item.action) {
            actionMap[item._id] = item.menuName;
          }
          if (item.children && !item.action) {
            deep(item.children);
          }
        }
      };
      deep(JSON.parse(JSON.stringify(list)))
      this.actionMap = actionMap;
    }
  },
};
</script>

<style lang="scss">
</style>